package com.example.administrator.qq;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.example.administrator.DB.DBManager;
import com.example.administrator.VO.UserInfo;
import com.example.administrator.VO.UserPoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ykbboom on 2016/12/31.
 */
/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link StepModelFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link StepModelFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class StepModelFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public static ImageButton pre;
    public static  ImageButton next;
    private ImageButton homePage;

    private DBManager dbManager;
    private ListView listView;
    private String[] TextArray = new String[5];//文本框显示排名和得分,前五
    private int[] ImageArray ={R.mipmap.one,R.mipmap.two,
            R.mipmap.three,R.mipmap.four,R.mipmap.five};
    private ArrayList<Map<String,Object>> mdata = new ArrayList<Map<String, Object>>();

    private OnFragmentInteractionListener mListener;

    public StepModelFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment StepModelFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static StepModelFragment newInstance(String param1, String param2) {
        StepModelFragment fragment = new StepModelFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_step_model, container, false);

        //初始化TextArray，存储前五名的得分，以"第一名："+time_point的形式存储到数组中
        dbManager = new DBManager(this.getActivity());
        List<UserPoint>userPoints = dbManager.queryFiveStepPoints();//取得排名前五的用户得分
        UserInfo userInfo = dbManager.queryAll();
        int index = 0;
        for(UserPoint userPoint:userPoints){
            String textArray = userInfo.getUser_name()+":"+String.valueOf(userPoint.getStep_point())+"分";
            TextArray[index] = textArray;
            index++;
        }

        //先初始化ArrayList<Map<String,Object>>mdata
        for(int i = 0;i<TextArray.length;i++){
            Map<String,Object>item = new HashMap<String,Object>();
            item.put("title",TextArray[i]);//排名
            item.put("image",ImageArray[i]);//排名图片
            mdata.add(item);
        }
        //构造适配器初始化ListView
        listView = (ListView) view.findViewById(R.id.listview2);
        SimpleAdapter simpleAdapter = new SimpleAdapter(this.getActivity(),mdata,R.layout.item,
                new String[]{"image","title"},new int[]{R.id.image,R.id.text});
        listView.setAdapter(simpleAdapter);
        //设置图片按钮事件，切换排行榜模式
        pre = (ImageButton) view.findViewById(R.id.pre);
        next = (ImageButton) view.findViewById(R.id.next);
        homePage = (ImageButton) view.findViewById(R.id.homepage);
        final FragmentManager manager = getActivity().getSupportFragmentManager();
        final Fragment fragment = manager.findFragmentByTag("timefragment");

        pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final FragmentTransaction transaction = manager.beginTransaction();
                transaction.show(fragment);
                transaction.commit();
            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final FragmentTransaction transaction2 = manager.beginTransaction();
                transaction2.show(fragment);
                transaction2.commit();
            }
        });
        homePage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(),MainActivity.class);
                startActivity(i);
            }
        });
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
//    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
